/*
 * Copyright 2002-2007 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.utils;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.internna.iwebmvc.utils.CollectionUtils;

/**
 * Utilities to read a Maven pom.xml and retrieve data.
 *
 * @author Jose Noheda
 * @since 1.0
 */
public final class ConcurrencyUtils {

    /**
     * Default private constructor for a Utility class.
     */
    private ConcurrencyUtils() {
        throw new AssertionError("Do not try to instantiate utility class");
    }

    /**
     * Launches a new thread for each task and optionally waits till all have finished.
     *
     * @param tasks any collection
     * @param awaitTermination true if the program flow should be halted till all tasks have finished.
     */
    public static boolean parallelExecution(Collection<? extends Runnable> tasks, boolean awaitTermination) {
        boolean success = true;
        if (CollectionUtils.isNotEmpty(tasks)) {
            Set<Future<?>> futures = new HashSet<Future<?>>(tasks.size());
            ExecutorService executor = Executors.newFixedThreadPool(tasks.size());
            for (Runnable task : tasks) {
                futures.add(executor.submit(task));
            }
            if (awaitTermination) {
                for (Future future : futures) {
                    try {
                        future.get();
                    } catch (InterruptedException ex) {
                        success = false;
                    } catch (ExecutionException ex) {
                       success = false;
                    }
                }
            }
        }
        return success;
    }

}
